package com.it.flowable.controller;

import com.it.flowable.dto.FormInfoDto;
import com.it.flowable.dto.NodeInfoDto;
import com.it.flowable.dto.ProcessDefinitionDto;
import com.it.flowable.dto.ProcessModelVo;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.*;
import org.flowable.bpmn.model.Process;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/api/model")
public class ProcessModelController {

    @Resource
    private RepositoryService repositoryService;

    /**
     * 部署新流程（私有方法，供内部调用）
     */
    @PostMapping("/deployProcessModel")
    public Deployment deployProcess(@RequestBody ProcessModelVo processModelVo) {
        Deployment res = repositoryService.createDeployment()
                .addString(processModelVo.getKey() + ".bpmn20.xml", processModelVo.getBpmnXml())
                .key(processModelVo.getKey())
                .name(processModelVo.getName())
                .deploy();
        return res;
    }

    /**
     * 分页 查询所有流程
     */
    @GetMapping("/getPage")
    public List<ProcessDefinitionDto> getPage() {
        List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery()
                .latestVersion()
                .orderByProcessDefinitionName().asc()
                .list();

        List<ProcessDefinitionDto> result = new ArrayList<>();

        for (ProcessDefinition processDefinition : list) {
            ProcessDefinitionDto dto = new ProcessDefinitionDto(processDefinition);

            // 设置部署时间
            Deployment deployment = repositoryService.createDeploymentQuery()
                    .deploymentId(processDefinition.getDeploymentId())
                    .singleResult();
            if (deployment != null) {
                dto.setDeploymentTime(deployment.getDeploymentTime());
            }

            // 获取BPMN模型
            BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
            if (bpmnModel != null) {
                // 提取节点信息
                extractNodeInfo(bpmnModel, dto);

                // 提取流程属性
                // 流程变量
                extractProcessVariables(bpmnModel, dto);
            }

            result.add(dto);
        }

        return result;
    }


    /**
     * 更新流程定义（重新部署新版本）
     */
    @PostMapping("/updateProcessDefinition")
    public String updateProcessDefinition(@RequestBody ProcessModelVo processModelVo) {
        String processDefinitionKey = processModelVo.getKey();
        // 1. 检查旧版本是否存在
        long count = repositoryService.createProcessDefinitionQuery().processDefinitionKey(processDefinitionKey).count();
        if (count == 0) {
            throw new RuntimeException("不存在");
        }
        // 2. 挂起旧版本的所有流程定义（防止新实例启动）
        repositoryService.suspendProcessDefinitionByKey(processDefinitionKey);
        log.info("已挂起旧版本流程定义: {}", processDefinitionKey);

        // 3. 重新部署新版本
        deployProcess(processModelVo);
        // 4. 激活新版本（如果需要立即启用）
        repositoryService.activateProcessDefinitionByKey(processDefinitionKey);
        return processDefinitionKey;
    }

    /**
     * 删除流程定义（包括所有版本）
     */
    @PostMapping("/deleteProcessModel")
    public void deleteProcessDefinition(String processDefinitionKey) {
        // 1. 查询所有版本的流程定义
        List<ProcessDefinition> processDefinitions = repositoryService
                .createProcessDefinitionQuery()
                .processDefinitionKey(processDefinitionKey)
                .list();

        if (processDefinitions.isEmpty()) {
            log.warn("流程定义不存在: {}", processDefinitionKey);
            return;
        }

        // 2. 逐个删除（包括关联的部署资源）
        for (ProcessDefinition definition : processDefinitions) {
            String deploymentId = definition.getDeploymentId();

            // 先挂起所有流程实例（可选，安全措施）
            repositoryService.suspendProcessDefinitionById(definition.getId());

            // 删除部署（cascade=true 会同时删除流程实例、历史数据等）
            repositoryService.deleteDeployment(deploymentId, true);

            log.info("已删除流程定义: {} (版本: {})", definition.getKey(), definition.getVersion());
        }
        log.info("成功删除所有版本的流程定义: {}", processDefinitionKey);
    }

    private void extractNodeInfo(BpmnModel bpmnModel, ProcessDefinitionDto dto) {
        Collection<FlowElement> flowElements = bpmnModel.getMainProcess().getFlowElements();

        for (FlowElement flowElement : flowElements) {
            NodeInfoDto nodeInfo = new NodeInfoDto();
            nodeInfo.setId(flowElement.getId());
            nodeInfo.setName(flowElement.getName());
            nodeInfo.setType(getElementType(flowElement));

            // 处理文档说明
            if (flowElement.getDocumentation() != null && !flowElement.getDocumentation().isEmpty()) {
                nodeInfo.setDocumentation(flowElement.getDocumentation());
            }
            // 处理ExecutionListeners
            for (FlowableListener listener : flowElement.getExecutionListeners()) {
                nodeInfo.getListeners().add(String.format("%s:%s:%s",
                        listener.getEvent(),
                        listener.getImplementationType(),
                        listener.getImplementation()));
            }
            //
            dto.setAttributes(flowElement.getAttributes());

            // 提取表单信息
            extractFormInfo(flowElement, nodeInfo);

            // 根据不同类型处理特定属性
            processElementSpecificProperties(flowElement, nodeInfo);

            // 处理扩展属性
            processExtensionElements(flowElement, nodeInfo);

            dto.getNodes().add(nodeInfo);
        }
    }

    private String getElementType(FlowElement element) {
        if (element instanceof StartEvent) return "StartEvent";
        if (element instanceof EndEvent) return "EndEvent";

        if (element instanceof UserTask) return "UserTask";
        if (element instanceof ServiceTask) return "ServiceTask";
        if (element instanceof ScriptTask) return "ScriptTask";
        if (element instanceof BusinessRuleTask) return "BusinessRuleTask";

        if (element instanceof ExclusiveGateway) return "ExclusiveGateway";
        if (element instanceof ParallelGateway) return "ParallelGateway";
        if (element instanceof InclusiveGateway) return "InclusiveGateway";
        // if (element instanceof EventBasedGateway) return "EventBasedGateway";

        if (element instanceof CallActivity) return "CallActivity";
        if (element instanceof SubProcess) return "SubProcess";
        return element.getClass().getSimpleName();
    }

    private void processElementSpecificProperties(FlowElement element, NodeInfoDto nodeInfo) {
        //
        if (element instanceof StartEvent) {
            StartEvent startEvent = (StartEvent) element;
            nodeInfo.setFormKey(startEvent.getFormKey());

            // 处理启动器
            if (startEvent.getInitiator() != null) {
                nodeInfo.getCustomExtensions().put("initiator", startEvent.getInitiator());
            }
        } else if (element instanceof UserTask) {
            UserTask userTask = (UserTask) element;
            nodeInfo.setAssignee(userTask.getAssignee());
            nodeInfo.setCandidateUsers(userTask.getCandidateUsers());
            nodeInfo.setCandidateGroups(userTask.getCandidateGroups());
            nodeInfo.setDueDate(userTask.getDueDate());
            nodeInfo.setPriority(userTask.getPriority());
            nodeInfo.setFormKey(userTask.getFormKey());

            // 处理任务监听器
            processTaskListeners(userTask, nodeInfo);
        } else if (element instanceof ServiceTask) {
            ServiceTask serviceTask = (ServiceTask) element;
            nodeInfo.getCustomExtensions().put("implementation", serviceTask.getImplementation());
            nodeInfo.getCustomExtensions().put("implementationType", serviceTask.getImplementationType());
            nodeInfo.getCustomExtensions().put("resultVariableName", serviceTask.getResultVariableName());
        } else if (element instanceof ScriptTask) {
            ScriptTask scriptTask = (ScriptTask) element;
            nodeInfo.getCustomExtensions().put("scriptFormat", scriptTask.getScriptFormat());
            if (scriptTask.getScript() != null) {
                nodeInfo.getCustomExtensions().put("script", scriptTask.getScript());
            }
        } else if (element instanceof CallActivity) {
            CallActivity callActivity = (CallActivity) element;
            nodeInfo.getCustomExtensions().put("calledElement", callActivity.getCalledElement());
            nodeInfo.getCustomExtensions().put("businessKey", callActivity.getBusinessKey());
        }
    }

    private void processTaskListeners(UserTask userTask, NodeInfoDto nodeInfo) {
        if (userTask.getTaskListeners() != null) {
            for (FlowableListener listener : userTask.getTaskListeners()) {
                String listenerInfo = String.format("%s:%s:%s",
                        listener.getEvent(),
                        listener.getImplementationType(),
                        listener.getImplementation());
                nodeInfo.getTaskListeners().add(listenerInfo);
            }
        }
    }

    private void extractFormInfo(FlowElement flowElement, NodeInfoDto nodeInfo) {
        // 开始事件表单
        if (flowElement instanceof StartEvent) {
            for (FormProperty formProperty : ((StartEvent) flowElement).getFormProperties()) {
                FormInfoDto formInfo = new FormInfoDto(formProperty);
                nodeInfo.getForms().add(formInfo);
            }
        } else if (flowElement instanceof UserTask) {
            for (FormProperty formProperty : ((UserTask) flowElement).getFormProperties()) {
                FormInfoDto formInfo = new FormInfoDto(formProperty);
                nodeInfo.getForms().add(formInfo);
            }
        }
    }

    private void extractProcessVariables(BpmnModel bpmnModel, ProcessDefinitionDto dto) {
        Process process = bpmnModel.getMainProcess();

    }

    private void processExtensionElements(FlowElement element, NodeInfoDto nodeInfo) {
        if (element.getExtensionElements() != null) {
            for (Map.Entry<String, List<ExtensionElement>> entry : element.getExtensionElements().entrySet()) {
                for (ExtensionElement extensionElement : entry.getValue()) {
                    // 处理字段扩展
                    if ("fields".equals(entry.getKey())) {
                        processFieldsExtension(extensionElement, nodeInfo);
                    }
                    // 处理其他扩展属性
                    processCustomExtensions(extensionElement, nodeInfo);
                }
            }
        }
    }

    private void processFieldsExtension(ExtensionElement extensionElement, NodeInfoDto nodeInfo) {
        List<ExtensionElement> fields = extensionElement.getChildElements().get("field");
        if (fields != null) {
            for (ExtensionElement field : fields) {
                String fieldName = field.getAttributeValue(null, "name");
                String fieldValue = field.getAttributeValue(null, "stringValue");
                if (fieldValue == null) {
                    ExtensionElement stringValue = field.getChildElements().get("string").get(0);
                    if (stringValue != null) {
                        fieldValue = stringValue.getElementText();
                    }
                }
                nodeInfo.getCustomExtensions().put("field_" + fieldName, fieldValue);
            }
        }
    }

    private void processCustomExtensions(ExtensionElement extensionElement, NodeInfoDto nodeInfo) {
        String extensionName = extensionElement.getName();
        String namespace = extensionElement.getNamespace();

        // 处理不同命名空间的扩展元素
        if (namespace != null) {
            switch (namespace) {
                case "http://activiti.org/modeler":
                    processModelerExtensions(extensionElement, nodeInfo);
                    break;
                case "http://flowable.org/bpmn":
                    processFlowableExtensions(extensionElement, nodeInfo);
                    break;
                case "http://camunda.org/schema/1.0/bpmn":
                    processCamundaExtensions(extensionElement, nodeInfo);
                    break;
                default:
                    processGenericExtensions(extensionElement, nodeInfo);
                    break;
            }
        } else {
            processGenericExtensions(extensionElement, nodeInfo);
        }
    }

    private void processModelerExtensions(ExtensionElement extensionElement, NodeInfoDto nodeInfo) {
        String extensionName = extensionElement.getName();

        switch (extensionName) {
            case "formproperty":
                processFormPropertyExtension(extensionElement, nodeInfo);
                break;
            case "executionlistener":
                processExecutionListenerExtension(extensionElement, nodeInfo);
                break;
            case "tasklistener":
                processTaskListenerExtension(extensionElement, nodeInfo);
                break;
            case "properties":
                processPropertiesExtension(extensionElement, nodeInfo);
                break;
            default:
                processGenericExtensionElement(extensionElement, nodeInfo);
                break;
        }
    }

    private void processFlowableExtensions(ExtensionElement extensionElement, NodeInfoDto nodeInfo) {
        String extensionName = extensionElement.getName();

        switch (extensionName) {
            case "failedJobRetryTimeCycle":
                nodeInfo.getCustomExtensions().put("failedJobRetryTimeCycle",
                        extensionElement.getElementText());
                break;
            case "executionListener":
                processFlowableExecutionListener(extensionElement, nodeInfo);
                break;
            case "taskListener":
                // processFlowableTaskListener(extensionElement, nodeInfo);
                break;
            case "formProperty":
                processFlowableFormProperty(extensionElement, nodeInfo);
                break;
            case "in":
            case "out":
                // processFlowableVariables(extensionElement, nodeInfo);
                break;
            default:
                processGenericExtensionElement(extensionElement, nodeInfo);
                break;
        }
    }

    private void processCamundaExtensions(ExtensionElement extensionElement, NodeInfoDto nodeInfo) {
        String extensionName = extensionElement.getName();

        switch (extensionName) {
            case "connector":
                // processCamundaConnector(extensionElement, nodeInfo);
                break;
            case "inputOutput":
                // processCamundaInputOutput(extensionElement, nodeInfo);
                break;
            case "executionListener":
                // processCamundaExecutionListener(extensionElement, nodeInfo);
                break;
            case "formData":
                processCamundaFormData(extensionElement, nodeInfo);
                break;
            case "constraint":
                // processCamundaConstraint(extensionElement, nodeInfo);
                break;
            case "failedJobRetryTimeCycle":
                nodeInfo.getCustomExtensions().put("camundaFailedJobRetryTimeCycle",
                        extensionElement.getElementText());
                break;
            case "priority":
                nodeInfo.getCustomExtensions().put("camundaPriority",
                        extensionElement.getElementText());
                break;
            default:
                processGenericExtensionElement(extensionElement, nodeInfo);
                break;
        }
    }

    private void processFormPropertyExtension(ExtensionElement extensionElement, NodeInfoDto nodeInfo) {
        Map<String, String> formProperties = new HashMap<>();

        String id = extensionElement.getAttributeValue(null, "id");
        String name = extensionElement.getAttributeValue(null, "name");
        String type = extensionElement.getAttributeValue(null, "type");
        String required = extensionElement.getAttributeValue(null, "required");
        String readable = extensionElement.getAttributeValue(null, "readable");
        String writable = extensionElement.getAttributeValue(null, "writable");

        if (id != null) {
            formProperties.put("id", id);
        }
        if (name != null) {
            formProperties.put("name", name);
        }
        if (type != null) {
            formProperties.put("type", type);
        }
        if (required != null) {
            formProperties.put("required", required);
        }
        if (readable != null) {
            formProperties.put("readable", readable);
        }
        if (writable != null) {
            formProperties.put("writable", writable);
        }

        // 处理枚举值
        List<ExtensionElement> enumElements = extensionElement.getChildElements().get("formvalue");
        if (enumElements != null && !enumElements.isEmpty()) {
            List<String> enumValues = new ArrayList<>();
            for (ExtensionElement enumElement : enumElements) {
                String enumId = enumElement.getAttributeValue(null, "id");
                String enumName = enumElement.getAttributeValue(null, "name");
                if (enumName != null) {
                    enumValues.add(enumName);
                }
            }
            formProperties.put("enumValues", String.join(",", enumValues));
        }

        nodeInfo.getCustomExtensions().put("formProperty_" + (id != null ? id : "unknown"), formProperties);
    }

    private void processExecutionListenerExtension(ExtensionElement extensionElement, NodeInfoDto nodeInfo) {
        String event = extensionElement.getAttributeValue(null, "event");
        String expression = extensionElement.getAttributeValue(null, "expression");
        String delegateExpression = extensionElement.getAttributeValue(null, "delegateExpression");
        String className = extensionElement.getAttributeValue(null, "class");

        Map<String, String> listenerInfo = new HashMap<>();
        listenerInfo.put("event", event != null ? event : "");

        if (expression != null) {
            listenerInfo.put("type", "expression");
            listenerInfo.put("value", expression);
        } else if (delegateExpression != null) {
            listenerInfo.put("type", "delegateExpression");
            listenerInfo.put("value", delegateExpression);
        } else if (className != null) {
            listenerInfo.put("type", "class");
            listenerInfo.put("value", className);
        }

        // 处理字段
        List<ExtensionElement> fieldElements = extensionElement.getChildElements().get("field");
        if (fieldElements != null && !fieldElements.isEmpty()) {
            Map<String, String> fields = new HashMap<>();
            for (ExtensionElement fieldElement : fieldElements) {
                String fieldName = fieldElement.getAttributeValue(null, "name");
                String fieldValue = getFieldValue(fieldElement);
                if (fieldValue != null) {
                    fields.put(fieldName, fieldValue);
                }
            }
            listenerInfo.put("fields", fields.toString());
        }

        nodeInfo.getCustomExtensions().put("executionListener_" + event, listenerInfo);
    }

    private void processTaskListenerExtension(ExtensionElement extensionElement, NodeInfoDto nodeInfo) {
        String event = extensionElement.getAttributeValue(null, "event");
        String expression = extensionElement.getAttributeValue(null, "expression");
        String delegateExpression = extensionElement.getAttributeValue(null, "delegateExpression");
        String className = extensionElement.getAttributeValue(null, "class");

        Map<String, String> listenerInfo = new HashMap<>();
        listenerInfo.put("event", event != null ? event : "");

        if (expression != null) {
            listenerInfo.put("type", "expression");
            listenerInfo.put("value", expression);
        } else if (delegateExpression != null) {
            listenerInfo.put("type", "delegateExpression");
            listenerInfo.put("value", delegateExpression);
        } else if (className != null) {
            listenerInfo.put("type", "class");
            listenerInfo.put("value", className);
        }

        nodeInfo.getCustomExtensions().put("taskListener_" + event, listenerInfo);
    }

    private void processPropertiesExtension(ExtensionElement extensionElement, NodeInfoDto nodeInfo) {
        List<ExtensionElement> propertyElements = extensionElement.getChildElements().get("property");
        if (propertyElements != null) {
            for (ExtensionElement propertyElement : propertyElements) {
                String name = propertyElement.getAttributeValue(null, "name");
                String value = propertyElement.getAttributeValue(null, "value");
                if (name != null && value != null) {
                    nodeInfo.getCustomExtensions().put("property_" + name, value);
                }
            }
        }
    }

    private void processFlowableExecutionListener(ExtensionElement extensionElement, NodeInfoDto nodeInfo) {
        String event = extensionElement.getAttributeValue(null, "event");
        String expression = extensionElement.getAttributeValue(null, "expression");
        String delegateExpression = extensionElement.getAttributeValue(null, "delegateExpression");
        String className = extensionElement.getAttributeValue(null, "class");

        Map<String, String> listenerInfo = new HashMap<>();
        listenerInfo.put("event", event != null ? event : "");

        if (expression != null) {
            listenerInfo.put("type", "expression");
            listenerInfo.put("value", expression);
        } else if (delegateExpression != null) {
            listenerInfo.put("type", "delegateExpression");
            listenerInfo.put("value", delegateExpression);
        } else if (className != null) {
            listenerInfo.put("type", "class");
            listenerInfo.put("value", className);
        }

        nodeInfo.getCustomExtensions().put("flowableExecutionListener_" + event, listenerInfo);
    }

    private void processFlowableFormProperty(ExtensionElement extensionElement, NodeInfoDto nodeInfo) {
        String id = extensionElement.getAttributeValue(null, "id");
        String name = extensionElement.getAttributeValue(null, "name");
        String type = extensionElement.getAttributeValue(null, "type");
        String expression = extensionElement.getAttributeValue(null, "expression");
        String variable = extensionElement.getAttributeValue(null, "variable");
        String required = extensionElement.getAttributeValue(null, "required");
        String readable = extensionElement.getAttributeValue(null, "readable");
        String writable = extensionElement.getAttributeValue(null, "writable");

        Map<String, String> formProperty = new HashMap<>();
        if (id != null) formProperty.put("id", id);
        if (name != null) formProperty.put("name", name);
        if (type != null) formProperty.put("type", type);
        if (expression != null) formProperty.put("expression", expression);
        if (variable != null) formProperty.put("variable", variable);
        if (required != null) formProperty.put("required", required);
        if (readable != null) formProperty.put("readable", readable);
        if (writable != null) formProperty.put("writable", writable);

        // 处理值
        List<ExtensionElement> valueElements = extensionElement.getChildElements().get("value");
        if (valueElements != null && !valueElements.isEmpty()) {
            List<String> values = new ArrayList<>();
            for (ExtensionElement valueElement : valueElements) {
                String valueId = valueElement.getAttributeValue(null, "id");
                String valueName = valueElement.getAttributeValue(null, "name");
                if (valueName != null) {
                    values.add(valueName);
                }
            }
            formProperty.put("values", String.join(",", values));
        }

        nodeInfo.getCustomExtensions().put("flowableFormProperty_" + (id != null ? id : "unknown"), formProperty);
    }

    private void processCamundaFormData(ExtensionElement extensionElement, NodeInfoDto nodeInfo) {
        List<ExtensionElement> formFieldElements = extensionElement.getChildElements().get("formField");
        if (formFieldElements != null) {
            List<Map<String, String>> formFields = new ArrayList<>();
            for (ExtensionElement formFieldElement : formFieldElements) {
                Map<String, String> formField = new HashMap<>();

                String id = formFieldElement.getAttributeValue(null, "id");
                String label = formFieldElement.getAttributeValue(null, "label");
                String type = formFieldElement.getAttributeValue(null, "type");
                String defaultValue = formFieldElement.getAttributeValue(null, "defaultValue");

                if (id != null) formField.put("id", id);
                if (label != null) formField.put("label", label);
                if (type != null) formField.put("type", type);
                if (defaultValue != null) formField.put("defaultValue", defaultValue);

                // 处理属性
                List<ExtensionElement> propertyElements = formFieldElement.getChildElements().get("properties");
                if (propertyElements != null && !propertyElements.isEmpty()) {
                    Map<String, String> properties = new HashMap<>();
                    List<ExtensionElement> propElements = propertyElements.get(0).getChildElements().get("property");
                    for (ExtensionElement propElement : propElements) {
                        String propId = propElement.getAttributeValue(null, "id");
                        String propValue = propElement.getAttributeValue(null, "value");
                        if (propId != null) {
                            properties.put(propId, propValue);
                        }
                    }
                    formField.put("properties", properties.toString());
                }

                // 处理验证
                List<ExtensionElement> validationElements = formFieldElement.getChildElements().get("validation");
                if (validationElements != null && !validationElements.isEmpty()) {
                    List<ExtensionElement> constraintElements = validationElements.get(0).getChildElements().get("constraint");
                    if (constraintElements != null && !constraintElements.isEmpty()) {
                        List<String> constraints = new ArrayList<>();
                        for (ExtensionElement constraintElement : constraintElements) {
                            String constraintName = constraintElement.getAttributeValue(null, "name");
                            String constraintConfig = constraintElement.getAttributeValue(null, "config");
                            if (constraintName != null) {
                                constraints.add(constraintName + (constraintConfig != null ? ":" + constraintConfig : ""));
                            }
                        }
                        formField.put("constraints", String.join(",", constraints));
                    }
                }

                formFields.add(formField);
            }
            nodeInfo.getCustomExtensions().put("camundaFormFields", formFields.toString());
        }
    }

    private void processGenericExtensions(ExtensionElement extensionElement, NodeInfoDto nodeInfo) {
        String extensionName = extensionElement.getName();

        // 处理简单文本内容
        if (extensionElement.getElementText() != null && !extensionElement.getElementText().trim().isEmpty()) {
            nodeInfo.getCustomExtensions().put(extensionName, extensionElement.getElementText().trim());
        }

        // 处理属性
        Map<String, List<ExtensionAttribute>> attributes = extensionElement.getAttributes();
        for (Map.Entry<String, List<ExtensionAttribute>> attr : attributes.entrySet()) {
            nodeInfo.getCustomExtensions().put(extensionName + "_" + attr.getKey(), attr.getValue());
        }

        // 处理子元素
        if (extensionElement.getChildElements() != null && !extensionElement.getChildElements().isEmpty()) {
            for (Map.Entry<String, List<ExtensionElement>> childEntry : extensionElement.getChildElements().entrySet()) {
                for (ExtensionElement childElement : childEntry.getValue()) {
                    processGenericExtensionElement(childElement, nodeInfo);
                }
            }
        }
    }

    private void processGenericExtensionElement(ExtensionElement extensionElement, NodeInfoDto nodeInfo) {
        String elementName = extensionElement.getName();

        // 如果有文本内容
        if (extensionElement.getElementText() != null && !extensionElement.getElementText().trim().isEmpty()) {
            nodeInfo.getCustomExtensions().put(elementName, extensionElement.getElementText().trim());
        }

        // 处理属性
        Map<String, List<ExtensionAttribute>> attributes = extensionElement.getAttributes();
        for (Map.Entry<String, List<ExtensionAttribute>> attr : attributes.entrySet()) {
            nodeInfo.getCustomExtensions().put(elementName + "_attr_" + attr.getKey(), attr.getValue());
        }
    }

    private String getFieldValue(ExtensionElement fieldElement) {
        // 尝试获取字符串值
        String stringValue = fieldElement.getAttributeValue(null, "stringValue");
        if (stringValue != null) {
            return stringValue;
        }

        // 尝试从子元素获取
        List<ExtensionElement> stringElements = fieldElement.getChildElements().get("string");
        if (stringElements != null && !stringElements.isEmpty()) {
            return stringElements.get(0).getElementText();
        }

        List<ExtensionElement> expressionElements = fieldElement.getChildElements().get("expression");
        if (expressionElements != null && !expressionElements.isEmpty()) {
            return expressionElements.get(0).getElementText();
        }

        return null;
    }
}